package com.fancy.application.sys.auth.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.util.StrUtil;
import com.fancy.application.common.utils.RedisUtil;
import com.fancy.application.sys.auth.service.ILoginService;
import com.fancy.application.sys.config.constants.ConfigConstants;
import com.fancy.application.sys.config.service.ISysConfigMainService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Log4j2
@Service
public class LoginService implements ILoginService {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private ISysConfigMainService sysConfigMainService;
    /**
     * 条形生成验证码
     * @return
     */
    public LineCaptcha generateLineCaptchaImg() {
        return CaptchaUtil.createLineCaptcha(110, 38);
        //return "data:image/jpeg;base64,"+lineCaptcha.getImageBase64();
    }

    public CaptchaImg getCaptchaImg(){
        String value = sysConfigMainService.getSystemValueByName(ConfigConstants.CAPTCHA_ENABLED);
        CaptchaImg captchaImg = new CaptchaImg();
        if("true".equals(value)){
            LineCaptcha  lineCaptcha = this.generateLineCaptchaImg();
            captchaImg.setImgData("data:image/jpeg;base64,"+lineCaptcha.getImageBase64());
            String code = lineCaptcha.getCode();
            redisUtil.set(captchaImg.getKey(),code,RedisUtil.MINUTES);
            log.debug("验证码生成成功！");
        }else{
            captchaImg.setKey("");
            captchaImg.setImgData("");
        }
        return captchaImg;
    }

    @Override
    public Boolean validateCaptcha(String captchaCode, String captchaKey) {
        String value = sysConfigMainService.getSystemValueByName(ConfigConstants.CAPTCHA_ENABLED);
        if("false".equals(value))return Boolean.TRUE;
        String code = (String) redisUtil.get(captchaKey);
        return StrUtil.equals(code, captchaCode);
    }
}
